package com.qianli.cashmama.trade.application.trade;

import com.alibaba.fastjson.JSON;
import com.fqgj.base.services.redis.RedisClient;
import com.fqgj.common.api.Response;
import com.fqgj.common.api.annotations.ParamsValidate;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.exception.common.ApplicationException;
import com.fqgj.exception.enums.BasicErrorCodeEnum;
import com.fqgj.xjd.user.client.UserHighmarkService;
import com.fqgj.xjd.user.client.enums.UserEventTrackEnum;
import com.fqgj.xjd.user.client.request.UserHighmarkVo;
import com.fqgj.xjd.user.client.response.User;
import com.qianli.cashmama.product.facade.result.ProductCategory;
import com.qianli.cashmama.trade.application.contract.ContractService;
import com.qianli.cashmama.trade.bean.RedisKeyConstant;
import com.qianli.cashmama.trade.client.trade.TradeApplicationService;
import com.qianli.cashmama.trade.client.trade.request.*;
import com.qianli.cashmama.trade.client.trade.response.CreatePaySuccessTradeResponse;
import com.qianli.cashmama.trade.client.trade.response.CreateServiceResponse;
import com.qianli.cashmama.trade.client.trade.response.CreateTradeResponse;
import com.qianli.cashmama.trade.client.trade.response.ServiceFeePayResponse;
import com.qianli.cashmama.trade.common.enums.*;
import com.qianli.cashmama.trade.common.error.TradeErrorCodeEnum;
import com.qianli.cashmama.trade.common.exceptions.TradeException;
import com.qianli.cashmama.trade.common.mq.MQTradeActionEnum;
import com.qianli.cashmama.trade.common.utils.MessageManager;
import com.qianli.cashmama.trade.common.utils.RebindCardUtil;
import com.qianli.cashmama.trade.common.utils.TradeConfigUtil;
import com.qianli.cashmama.trade.dao.*;
import com.qianli.cashmama.trade.domain.factory.BillBaseDomainFactory;
import com.qianli.cashmama.trade.domain.factory.TradeBaseDomainFactory;
import com.qianli.cashmama.trade.domain.model.*;
import com.qianli.cashmama.trade.domain.services.TradeBaseService;
import com.qianli.cashmama.trade.entity.*;
import com.qianli.cashmama.trade.integration.audit.AuditIntegrationService;
import com.qianli.cashmama.trade.integration.notification.message.MessageIntegrationService;
import com.qianli.cashmama.trade.integration.product.ProductIntegrationService;
import com.qianli.cashmama.trade.integration.product.dto.ProductDto;
import com.qianli.cashmama.trade.integration.product.dto.ProductRequestDTO;
import com.qianli.cashmama.trade.integration.user.UserIntegrationService;
import com.qianli.cashmama.trade.mq.MQOpenapiHelpUtils;
import com.qianli.cashmama.trade.repo.*;
import com.qianli.cashmama.trade.unique.BillUniqueService;
import com.qianli.cashmama.trade.unique.TradeUniqueService;
import com.robert.vesta.util.IdUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2017/7/20
 * Time: 上午9:32
 */
@Service("tradeApplicationService")
public class TradeApplicationServiceImpl implements TradeApplicationService {
    private static final Logger LOGGER = LoggerFactory.getLogger(TradeApplicationServiceImpl.class);

    /**
     * 服务费利率
     */
    private static final String HIGH_MARK_TRADE_NO = "highMark_{tradeNo}";

    @Autowired
    private TradeBaseDomainFactory tradeBaseDomainFactory;

    @Autowired
    private TradeBaseService tradeBaseService;

    @Autowired
    private TradeBaseRepository tradeBaseRepository;

    @Autowired
    private TradeUniqueService tradeUniqueService;

    @Autowired
    private TradeTaskCenterRepository tradeTaskCenterRepository;

    @Autowired
    private AuditIntegrationService auditIntegrationService;

    @Autowired
    private BillBaseRepository billBaseRepository;

    @Autowired
    private BillBaseDomainFactory billBaseDomainFactory;

    @Autowired
    private UserIntegrationService userIntegrationService;

    @Autowired
    private BillUniqueService billUniqueService;

    @Autowired
    private BizRecordRepository bizRecordRepository;

    @Autowired
    private MessageIntegrationService messageIntegrationService;

    @Autowired
    private TTradeContractDao tTradeContractDao;

    @Autowired
    private TimeoutRepository timeoutRepository;

    @Autowired
    private TradeConfigUtil tradeConfigUtil;

    @Autowired
    private UserHighmarkService userHighmarkService;

    @Autowired
    private ContractService contractService;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private TTradeExtraDao tTradeExtraDao;

    @Autowired
    private ProductIntegrationService productIntegrationService;

    @Autowired
    private TTradeOpenOrderDao tTradeOpenOrderDao;
    @Autowired
    private TServiceTradeDao tServiceTradeDao;

    @Autowired
    private TTradeDao tTradeDao;

    @Autowired
    private TBillDao tBillDao;

    /**
     * 创建交易
     *
     * @param createTradeRequest
     * @return
     */
    @Override
    @ParamsValidate
    public Response<CreateTradeResponse> createTrade(CreateTradeRequest createTradeRequest) {
        LOGGER.info("订单创建开始,createTradeRequest:{}", JSON.toJSONString(createTradeRequest));
        try {
            TradeBase tradeBase = tradeBaseDomainFactory.composeTradeBase(createTradeRequest);
            if (tradeBase == null) {
                throw new TradeException(TradeErrorCodeEnum.create_failed);
            }

            UniqueStatusEnum uniqueStatusEnum = tradeUniqueService.uniqueDecide(tradeBase);
            if (UniqueStatusEnum.EXIST == uniqueStatusEnum) {
                throw new TradeException(TradeErrorCodeEnum.create_failed, MessageManager.getMsg("multiple.transactions"));
            }

            tradeBaseService.createTrade(tradeBase);
            tradeBaseRepository.store(tradeBase);

            //附加信息
            handlerTradeExtraData(createTradeRequest.getTradeExtraData(), createTradeRequest.getUserCode(), tradeBase.getTradeNo());

            userIntegrationService.addUserEventTrack(tradeBase.getUserCode(), UserEventTrackEnum.e_app_order_create_done);

            return Response.ok().putData(new CreateTradeResponse(tradeBase.getTradeNo()));
        } catch (TradeException e) {
            LOGGER.info("创建交易失败1,userCode:{}", createTradeRequest.getUserCode(), e);
            return Response.error("create trade failed");
        } catch (Exception e) {
            LOGGER.error("创建交易失败2,userCode:{}", createTradeRequest.getUserCode(), e);
            return Response.error("create trade failed");
        } catch (Throwable e) {
            LOGGER.error("创建交易失败3,userCode:{}", createTradeRequest.getUserCode(), e);
            return Response.error("create trade failed");
        }
    }

    public Response<CreateTradeResponse> createTrade1(CreateTradeRequest createTradeRequest) {
        LOGGER.info("订单创建开始,createTradeRequest:{}", JSON.toJSONString(createTradeRequest));
        return Response.error(TradeErrorCodeEnum.create_failed);
    }


    public static void main(String[] args) {
        Response<Object> error = Response.error(TradeErrorCodeEnum.create_failed);
        System.err.println(111);

    }

    private void handlerTradeExtraData(TradeExtraData tradeExtraData, String userCode, String tradeNo) {
        if (tradeExtraData != null) {
            TTradeExtraEntity tTradeExtraEntity = new TTradeExtraEntity();
            BeanUtils.copyProperties(tradeExtraData, tTradeExtraEntity);
            tTradeExtraEntity.setTradeNo(tradeNo);
            tTradeExtraEntity.setUserCode(userCode);
            tTradeExtraDao.insert(tTradeExtraEntity);
        }
    }

    @Override
    @ParamsValidate
    public Response<CreateTradeResponse> createAuditSuccessTrade(CreateAuditSuccessTradeRequest request) {
        LOGGER.info("=== 审核通过订单开始创建,request:{} ===", JSON.toJSONString(request));
        if (new BigDecimal(request.getArrivalAmount()).compareTo(new BigDecimal(0)) <= 0 || new BigDecimal(request.getArrivalAmount()).compareTo(new BigDecimal(3200)) > 0) {
            return Response.error(BasicErrorCodeEnum.PARAM_VALID_ERROR, "arrivalAmount is invalid");
        }
        ProductDto productDto = productIntegrationService.getProductInfoByCode(request.getProductCode());
        if (productDto == null) {
            return Response.error(BasicErrorCodeEnum.PARAM_VALID_ERROR, "product not exist");
        }
        TradeBase tradeBase = tradeBaseDomainFactory.composeAuditSuccessTradeBase(request, productDto);
        UniqueStatusEnum uniqueStatusEnum = tradeUniqueService.uniqueDecideByType(request.getCategoryCode(), tradeBase.getTradeNo(), request.getUserCode(), UniqueRepeatTypeEnum.CREATE_TRADE.getType());
        if (UniqueStatusEnum.EXIST == uniqueStatusEnum) {
            throw new TradeException(TradeErrorCodeEnum.create_failed, MessageManager.getMsg("multiple.transactions"));
        }
        TTradeOpenOrderEntity tTradeOpenOrderEntity = new TTradeOpenOrderEntity();
        tTradeOpenOrderEntity.setCategoryCode(request.getCategoryCode());
        tTradeOpenOrderEntity.setUserCode(request.getUserCode());
        tTradeOpenOrderEntity.setOrderId(request.getOrderId());
        tTradeOpenOrderEntity.setTradeNo(tradeBase.getTradeNo());
        tTradeOpenOrderEntity.setBankName(request.getBankName());
        tTradeOpenOrderEntity.setBankNo(request.getBankNo());
        tTradeOpenOrderEntity.setIfscCode(request.getIfscCode());
        tTradeOpenOrderEntity.setPhone(request.getPhone());
        tTradeOpenOrderEntity.setEmail(request.getEmail());
        tTradeOpenOrderEntity.setAcctName(request.getAcctName());
        tTradeOpenOrderEntity.setArrivalAmount(new BigDecimal(request.getArrivalAmount()));
        tTradeOpenOrderEntity.setContractAmount(new BigDecimal(request.getContractAmount()));
        tTradeOpenOrderEntity.setOrderStaus(TradeStatusEnum.LOAN_WAITTING.getStatus());
        tTradeOpenOrderDao.insert(tTradeOpenOrderEntity);

        BizRecord bizRecord = new BizRecord()
                .setBizType(BizTypeEnum.TRADE_TO_PAY)
                .setInnerNo(tradeBase.getTradeNo())
                .setBizNo(tradeBase.getTradeNo());
        bizRecordRepository.store(bizRecord);

        tradeBaseRepository.store(tradeBase);

        //信审成功插入打款任务
        TradeTaskCenter tradeTaskCenter = new TradeTaskCenter()
                .setTaskRetryTimes(0)
                .setTaskStatus(TaskStatusEnum.INIT)
                .setTaskType(TaskTypeEnum.THIRD_ORDER_TO_PAY)
                .setTradeNo(tradeBase.getTradeNo())
                .setBizNo(tradeBase.getTradeNo());
        tradeTaskCenterRepository.store(tradeTaskCenter);
        LOGGER.info("== 审核通过订单创建成功 ==,entity:{}", JSON.toJSONString(tradeBase));
        return Response.ok().putData(new CreateTradeResponse(tradeBase.getTradeNo()));
    }

    @Override
    public Response<CreatePaySuccessTradeResponse> createPaySuccessTrade(CreatePaySuccessTradeRequest request) {
        LOGGER.info("=== 打款成功订单开始创建,request:{} ===", JSON.toJSONString(request));
        ProductRequestDTO requestDTO = new ProductRequestDTO();
        requestDTO.setPrincipalMoney(new BigDecimal(request.getArrivalAmount()).add(new BigDecimal(request.getCostFee())).toString());
        requestDTO.setArrivalMoney(request.getArrivalAmount());
        requestDTO.setPaybackPeriodLength(request.getLoanTerm());
        requestDTO.setTotalPaybackPeriodCount(1);
        requestDTO.setServiceCharge(request.getCostFee());
        requestDTO.setPreServiceCharge(new BigDecimal(request.getCostFee()).multiply(new BigDecimal(0.82)).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        requestDTO.setGstCharge(new BigDecimal(request.getCostFee()).multiply(new BigDecimal(0.18)).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        requestDTO.setOneTimeOnBoardingFee("0");
        requestDTO.setOverdueServiceCharge("100");
        requestDTO.setRate(request.getInterestRate());
        requestDTO.setPenaltyRate(request.getOverdueRate());
        requestDTO.setServiceFeeRate("0");
        requestDTO.setProductCategory(request.getProductCategory());
        requestDTO.setShelfType(2);
        requestDTO.setActive(true);
        requestDTO.setShowFlag("0");
        requestDTO.setRiskLevel(1);
        ProductDto productDto = productIntegrationService.getProductDetailByArrivalMoney(requestDTO);
        TradeBase tradeBase = tradeBaseDomainFactory.composePaySuccessTradeBase(request, productDto);

        tradeBaseRepository.store(tradeBase);

        //生成账单
        List<BillBase> billBaseList = billBaseDomainFactory.composeBillBase(tradeBase, request.getLoanTime());
        billBaseRepository.storeList(billBaseList);
        //若合同不存在 则重新生成
        if (StringUtils.isEmpty(tradeBase.getContractUrl())) {
            TimeoutEvent timeoutEvent = new TimeoutEvent()
                    .setType(TimeoutTypeEnum.CREATE_CONTRACT_JOB)
                    .setTriggerTime(DateUtils.addMinutes(new Date(), 1))
                    .setValue(tradeBase.getTradeNo());
            timeoutRepository.store(timeoutEvent);
        }
        LOGGER.info("=== 打款成功订单创建成功,request:{} ===", JSON.toJSONString(request));
        CreatePaySuccessTradeResponse response = new CreatePaySuccessTradeResponse();
        response.setTradeNo(tradeBase.getTradeNo());
        response.setProductCode(tradeBase.getProductCode());
        response.setProductCategory(tradeBase.getProductCategory());
        return Response.ok().putData(response);
    }

    /**
     * 信审回调
     *
     * @param auditResultRequest
     * @return
     */
    @Override
    public Response auditCallbackV2(AuditResultRequest auditResultRequest) {
        try {
            boolean sendToPay = false;
            boolean auditPass = false;
            LOGGER.info("auditCallbackV2,信审回调,auditResultRequest:{}", JSON.toJSONString(auditResultRequest));
            AuditResultTypeEnum auditResultType = AuditResultTypeEnum.getEnum(auditResultRequest.getResultType());
            TradeBase tradeBase = tradeBaseRepository.loadWithRisk(auditResultRequest.getTradeNo());
            if (tradeBase == null) {
                return Response.error(TradeErrorCodeEnum.trade_not_exist);
            }

            if (tradeBase.getTradeOrderStatus() != TradeStatusEnum.INIT && tradeBase.getTradeOrderStatus() != TradeStatusEnum.AUDIT_WATTING) {
                return Response.ok().putData(null);
            }
            boolean completed = tradeBase.getTradeOrderStatus().equals(TradeStatusEnum.EARLY_REPAYMENT) ||
                    tradeBase.getTradeOrderStatus().equals(TradeStatusEnum.OVERDUE_REPAYMENT) ||
                    tradeBase.getTradeOrderStatus().equals(TradeStatusEnum.OVERDUE_REPAYMENT) ||
                    tradeBase.getTradeOrderStatus().equals(TradeStatusEnum.MANUAL_CLOSED) ||
                    tradeBase.getTradeOrderStatus().equals(TradeStatusEnum.PAY_RETRY);
            if (completed) {
                return Response.error(TradeErrorCodeEnum.trade_closed_already);
            }

            tradeBase.setAuditDate(new Date());
            User user = userIntegrationService.getUserByUserCode(tradeBase.getUserCode());
            if (AuditResultTypeEnum.REJECT.equals(auditResultType)) {
                tradeBaseService.closeAuditRejectTrade(tradeBase);
                tradeUniqueService.releaseUniqueLock(tradeBase);
            } else if (AuditResultTypeEnum.PASS.equals(auditResultType)) {
                //先判断是否需要电子签
                if (tradeConfigUtil.getNeedEsignProcess().contains(tradeBase.getChannelCode())) {
                    tradeBaseService.auditPassToEsign(tradeBase);
                    LOGGER.info("===== 需要电子签章，tradeNo:{}, channelCode:{}, userCode:{} ======", tradeBase.getTradeNo(), tradeBase.getChannelCode(), tradeBase.getUserCode());
                } else {
                    ProductCategory productCategory = productIntegrationService.getCategoryByMerchantCode(tradeBase.getMerchantCode());
                    if (productCategory.getConfirmWithdrawProcess() == 1) {//有确认提现流程
                        this.withdraw(tradeBase, user);
                    } else {
                        tradeBaseService.auditPass(tradeBase);
                        sendToPay = true;
                        messageIntegrationService.sendMessageAfterAuditPass(tradeBase.getTradeNo(), tradeBase.getUserCode(), user.getMobile(), user.getName(), tradeBase.getBorrowTotalCapital().toString());
                    }
                }
                auditPass = true;
            } else if (AuditResultTypeEnum.WAITING_HIGHMARK.equals(auditResultType)) {
                tradeBase.setTradeAuditSubStatus(TradeAuditSubStatusEnum.WAITING_HIGHMARK);
                messageIntegrationService.sendMessageAfterNeedHighmark(tradeBase.getTradeNo(), tradeBase.getUserCode(), user.getMobile(), user.getName(), tradeBase.getBorrowTotalCapital().toString());
            } else {
                return Response.error(TradeErrorCodeEnum.default_error, "Result error");
            }

            //更新入库
            tradeBaseRepository.restore(tradeBase);

            if (sendToPay) {
                //信审成功插入打款任务
                TradeTaskCenter tradeTaskCenter = new TradeTaskCenter()
                        .setTaskRetryTimes(0)
                        .setTaskStatus(TaskStatusEnum.INIT)
                        .setTaskType(TaskTypeEnum.PAY)
                        .setTradeNo(tradeBase.getTradeNo())
                        .setBizNo(tradeBase.getTradeNo());
                tradeTaskCenterRepository.store(tradeTaskCenter);
            }

            //发送审核结果mq
            if (tradeBase.getChannelCode().contains("open_api")) {
                if (AuditResultTypeEnum.PASS.equals(auditResultType)) {
                    MQOpenapiHelpUtils.send(tradeBase.getTradeNo(), MQTradeActionEnum.AUDIT_PASS);
                } else if (AuditResultTypeEnum.REJECT.equals(auditResultType)) {
                    MQOpenapiHelpUtils.send(tradeBase.getTradeNo(), MQTradeActionEnum.AUDIT_REJECT);
                }
            }

            if (auditPass) {
                userIntegrationService.addUserEventTrack(tradeBase.getUserCode(), UserEventTrackEnum.e_app_order_audit_done);
            }

            LOGGER.info("auditCallbackV2,信审回调处理成功,tradeNo:{}", auditResultRequest.getTradeNo());
            return Response.ok().putData(null);
        } catch (TradeException e) {
            LOGGER.error("信审回调处理失败" + JSON.toJSONString(auditResultRequest), e);
            return Response.error(TradeErrorCodeEnum.trade_not_exist);
        } catch (Exception e) {
            LOGGER.error("信审回调处理异常" + JSON.toJSONString(auditResultRequest), e);
            return Response.error(TradeErrorCodeEnum.trade_not_exist);
        }
    }

    /**
     * 支付回调
     *
     * @param payResultRequest
     */
    @Override
    @ParamsValidate
    public Response payCallBack(PayResultRequest payResultRequest) {
        LOGGER.info("payCallBack,放款回执,tradeNo:{},payResultRequest:{}", payResultRequest.getTradeNo(), JSON.toJSONString(payResultRequest));
        String tradeNo = payResultRequest.getTradeNo();
        try {
            TradeBase tradeBase = tradeBaseRepository.load(tradeNo);
            if (tradeBase == null) {
                return Response.error(TradeErrorCodeEnum.trade_not_exist);
            }
            if (tradeBase.getTradeOrderStatus() == TradeStatusEnum.REPAYMENT_WATTING) {
                LOGGER.info("payCallBack,交易状态已经待还款==,tradeNo:{}", tradeBase.getTradeNo());
                return Response.ok().putData(null);
            }
            if (tradeBase.getTradeOrderStatus() != TradeStatusEnum.INIT && tradeBase.getTradeOrderStatus() != TradeStatusEnum.LOAN_WAITTING) {
                LOGGER.info("payCallBack,放款回执,交易状态不匹配==,tradeNo:{}", tradeBase.getTradeNo());
                return Response.error("交易状态不匹配");
            }

            UniqueStatusEnum uniqueStatusEnum = billUniqueService.uniqueDecide(tradeBase.getTradeNo(), tradeBase.getUserCode(), tradeBase.getProductCategory());
            if (uniqueStatusEnum.equals(UniqueStatusEnum.EXIST)) {
                LOGGER.info("==放款回执，交易账单已生成==,tradeNo:{}", tradeBase.getTradeNo());
                return Response.ok().putData(null);
            }

            if (payResultRequest.getPaySuccess()) {
                tradeBase.setReceivedDate(payResultRequest.getReceivedDate())
                        .setPayNo(payResultRequest.getPayBizNo())
                        .setCapitalCode(payResultRequest.getCapitalCode());
                //交易状态签转
                tradeBaseService.paymentSuccess(tradeBase);
                //生成账单
                List<BillBase> billBaseList = billBaseDomainFactory.composeBillBase(tradeBase, payResultRequest.getReceivedDate());
                billBaseRepository.storeList(billBaseList);
                //若合同不存在 则重新生成
                if (StringUtils.isEmpty(tradeBase.getContractUrl())) {
                    TimeoutEvent timeoutEvent = new TimeoutEvent()
                            .setType(TimeoutTypeEnum.CREATE_CONTRACT_JOB)
                            .setTriggerTime(DateUtils.addMinutes(new Date(), 1))
                            .setValue(tradeNo);
                    timeoutRepository.store(timeoutEvent);
                }
            } else {
                //重绑卡次数限制
                if (payResultRequest.getPayRetry()) {
                    String bizNo = RebindCardUtil.getRebindCardOutNo(tradeBase.getTradeNo());
                    BizRecord bizRecord = bizRecordRepository.load(bizNo);
                    if (bizRecord != null) {
                        LOGGER.error("重复重绑卡作关闭处理,tradeNo:{}", tradeBase.getTradeNo());
                        payResultRequest.setPayRetry(false);
                    }
                }

                tradeBaseService.loanFailed(tradeBase, payResultRequest.getPayRetry());
                if (payResultRequest.getPayRetry()) {
                    userIntegrationService.changeUserBankStatus(tradeBase.getUserCode());
                } else {
                    tradeUniqueService.releaseUniqueLock(tradeBase);
                }
            }

            tradeBaseRepository.restore(tradeBase);

            //发送审核结果mq
            if (tradeBase.getChannelCode().contains("open_api")) {
                if (payResultRequest.getPaySuccess()) {
                    MQOpenapiHelpUtils.send(tradeBase.getTradeNo(), MQTradeActionEnum.DISBURSE_SUCCESS);
                    //放款成功内部埋点
                    userIntegrationService.addUserEventTrack(tradeBase.getUserCode(), UserEventTrackEnum.e_app_order_deal_done);
                } else {
                    if (payResultRequest.getPayRetry()) {
                        MQOpenapiHelpUtils.send(tradeBase.getTradeNo(), MQTradeActionEnum.DISBURSE_FAIL_REBIND);
                    } else {
                        MQOpenapiHelpUtils.send(tradeBase.getTradeNo(), MQTradeActionEnum.DISBURSE_FAIL);
                    }
                }
            }
            try {
                TTradeExtraEntity tTradeExtraEntity = tTradeExtraDao.selectByTradeNo(tradeNo);
                if (tTradeExtraEntity != null && StringUtils.isNotEmpty(tTradeExtraEntity.getAppsflyerId())) {
                    messageIntegrationService.sendAppsflyerDataPush(tTradeExtraEntity.getPackageName(), tTradeExtraEntity.getAppsflyerId(), tTradeExtraEntity.getUserCode(), AppsFlyerEventEnum.DISBURSE_SUCCESS.getEventName(), String.valueOf(tradeBase.getReceivedTotalCapital()));
                    LOGGER.info("=== appsflyer放款成功埋点SUCCESS,tradeNo:{} ===", tradeNo);
                }
            } catch (Exception e) {
                LOGGER.error("=== appsflyer 埋点失败 e:{}===", e);
            }
            LOGGER.info("payCallBack,放款回执成功,tradeNo:{}", tradeNo);

            billUniqueService.releaseUniqueLock(tradeBase.getTradeNo(), tradeBase.getUserCode(), tradeBase.getProductCategory());
            return Response.ok().putData(null);
        } catch (TradeException e) {
            LOGGER.error("payCallBackError,放款回执处理失败,tradeNo:{}", tradeNo, e);
            return Response.error(TradeErrorCodeEnum.trade_not_exist);
        } catch (ApplicationException e) {
            LOGGER.error("payCallBackError,放款回执处理失败2,tradeNo:{}", tradeNo, e);
            return Response.error(TradeErrorCodeEnum.trade_not_exist);
        } catch (Exception e) {
            LOGGER.error("payCallBackError,放款回执处理异常,tradeNo:{}", tradeNo, e);
            return Response.error(TradeErrorCodeEnum.trade_not_exist);
        }
    }

    /**
     * 支付回调
     *
     * @param payResultRequest
     * @return
     */
    @Override
    @ParamsValidate
    @Transactional
    public Response payCallBackV2(PayResultRequest payResultRequest) {
        String bizNo = payResultRequest.getTradeNo();
        BizRecord bizRecord = bizRecordRepository.load(bizNo);

        payResultRequest.setTradeNo(bizRecord.getInnerNo());
        return payCallBack(payResultRequest);
    }

    @Override
    public Response payCallBackForOpenApi(PayResultRequest payResultRequest) {
        LOGGER.info("=== payCallBackForOpenApi,放款回执,tradeNo:{},payResultRequest:{} ===", payResultRequest.getTradeNo(), JSON.toJSONString(payResultRequest));

        TTradeOpenOrderEntity entity = tTradeOpenOrderDao.getByTradeNo(payResultRequest.getTradeNo());
        if (entity == null) {
            return Response.error(TradeErrorCodeEnum.trade_not_exist);
        }
        if (entity.getOrderStaus() == TradeStatusEnum.REPAYMENT_WATTING.getStatus()) {
            LOGGER.info("payCallBackForOpenApi, 已经待还款==, tradeNo:{}", entity.getTradeNo());
            return Response.ok();
        }
        TTradeOpenOrderEntity tTradeOpenOrderEntity = tTradeOpenOrderDao.getByTradeNo(payResultRequest.getTradeNo());
        if (tTradeOpenOrderEntity != null && tTradeOpenOrderEntity.getOrderStaus() == TradeStatusEnum.LOAN_WAITTING.getStatus()) {
            tTradeOpenOrderEntity.setOrderStaus(TradeStatusEnum.REPAYMENT_WATTING.getStatus());
            tTradeOpenOrderEntity.setFundCode(payResultRequest.getCapitalCode() != null ? payResultRequest.getCapitalCode().toString() : "");
            tTradeOpenOrderEntity.setPayNo(payResultRequest.getPayBizNo());
            tTradeOpenOrderEntity.setTripleReceiveDate(payResultRequest.getReceivedDate());
            tTradeOpenOrderDao.updateByPrimaryKey(tTradeOpenOrderEntity);
        }

        if (payResultRequest.getPaySuccess()) {
            MQOpenapiHelpUtils.send(payResultRequest.getTradeNo(), MQTradeActionEnum.DISBURSE_SUCCESS);
        } else {
            if (payResultRequest.getPayRetry()) {
                MQOpenapiHelpUtils.send(payResultRequest.getTradeNo(), MQTradeActionEnum.DISBURSE_FAIL_REBIND);
            } else {
                MQOpenapiHelpUtils.send(payResultRequest.getTradeNo(), MQTradeActionEnum.DISBURSE_FAIL);
            }
        }
        LOGGER.info("==== payCallBackForOpenApi,放款回执结束，tradeNo:{} ====", payResultRequest.getTradeNo());
        return Response.ok();
    }

    @Override
    public Response<ServiceFeePayResponse> serviceFeePayCallBack(ServiceFeePayResultRequest serviceFeePayResultRequest) {
        return Response.error(TradeErrorCodeEnum.default_error);
    }

    @Override
    @ParamsValidate
    public Response closeTrade(CloseTradeRequest closeTradeRequest) {
        LOGGER.info("== 关闭交易 ==,tradeNo:{}", closeTradeRequest.getTradeNo());
        try {
            TradeBase tradeBase = tradeBaseRepository.load(closeTradeRequest.getTradeNo());
            if (tradeBase == null) {
                return Response.error(TradeErrorCodeEnum.trade_not_exist);
            }
            int mqType = 0;
            if (tradeBase.getTradeOrderStatus() == TradeStatusEnum.INIT
                    || tradeBase.getTradeOrderStatus() == TradeStatusEnum.CREATE_SUCCESS
                    || tradeBase.getTradeOrderStatus() == TradeStatusEnum.AUDIT_WATTING) {
                mqType = 1;
            }

            tradeBase.transferStatus(TradeActionEnum.CLOSED.getCode()
                    , TradeStatusEnum.MANUAL_CLOSED.getStatus(), "jeff", new Date(), new Date(), "close trade");

            tradeUniqueService.releaseUniqueLock(tradeBase);
            tradeBaseRepository.restore(tradeBase);

            //发送审核结果mq
            if (mqType == 1 && tradeBase.getChannelCode().contains("open_api")) {
                LOGGER.info("关闭交易后发送mq,tradeNo:{}", closeTradeRequest.getTradeNo());
                MQOpenapiHelpUtils.send(tradeBase.getTradeNo(), MQTradeActionEnum.AUDIT_REJECT);
            }

            return Response.ok().putData(null);
        } catch (TradeException e) {
            LOGGER.error("== 关闭交易失败 ==,tradeNo:{}", closeTradeRequest.getTradeNo());
            return Response.error(e.getErrorEnum());
        }
    }

    /**
     * 重新发起支付（重绑卡）
     *
     * @param repayTradeRequest
     * @return
     */
    @Override
    @ParamsValidate
    public Response updateBankInfoAndLoan(RepayTradeRequest repayTradeRequest) {
        try {
            LOGGER.info("updateBankInfoAndLoan,开始重新绑卡,request:{}", repayTradeRequest);
            String tradeNo = repayTradeRequest.getTradeNo();
            TradeBase tradeBase = tradeBaseRepository.load(tradeNo);
            if (tradeBase == null) {
                return Response.error(TradeErrorCodeEnum.trade_not_exist);
            }
            if (!TradeStatusEnum.PAY_RETRY.equals(tradeBase.getTradeOrderStatus())) {
                return Response.error(TradeErrorCodeEnum.trade_status_check_error);
            }

            userIntegrationService.reBindCard(tradeBase.getUserCode(), repayTradeRequest.getBankType(), repayTradeRequest.getCardNo(), repayTradeRequest.getBankName());

            //更新银行卡信息
            TradeBank tradeBank = tradeBaseDomainFactory.composeTradeBank(repayTradeRequest, tradeBase.getTradeBank());
            tradeBase.setTradeBank(tradeBank);

            //重新放款
            tradeBase.setTradePayStatus(TradePayStatusEnum.INIT);
            tradeBase.transferStatus(TradeActionEnum.LOAN_RETRY.getCode(),
                    TradeStatusEnum.LOAN_WAITTING.getStatus(), "jeff", new Date(), new Date(), "update bank success");
            tradeBaseService.createPayTask(tradeBase, true);
            tradeBaseRepository.restore(tradeBase);
            LOGGER.info("updateBankInfoAndLoan,重新绑卡处理成功,request:{}", JSON.toJSONString(repayTradeRequest));
            return Response.ok().putData(null);
        } catch (TradeException e) {
            LOGGER.error("重新绑卡失败,request:{}", JSON.toJSONString(repayTradeRequest));
            return Response.error("Bind card error");
        } catch (Exception e) {
            LOGGER.error("重新绑卡异常,request:{}", JSON.toJSONString(repayTradeRequest));
            return Response.error("Bind card error");
        }
    }

    @Override
    public Response updateBankInfoAndLoanMarket(RepayTradeRequest repayTradeRequest) {
        try {
            LOGGER.info("updateBankInfoAndLoanMarket,开始重新绑卡,request:{}", repayTradeRequest);
            String tradeNo = repayTradeRequest.getTradeNo();
            TradeBase tradeBase = tradeBaseRepository.load(tradeNo);
            if (tradeBase == null) {
                return Response.error(TradeErrorCodeEnum.trade_not_exist);
            }
            if (!TradeStatusEnum.PAY_RETRY.equals(tradeBase.getTradeOrderStatus())) {
                return Response.error(TradeErrorCodeEnum.trade_status_check_error);
            }

            userIntegrationService.reBindCard(tradeBase.getUserCode(), repayTradeRequest.getBankType(), repayTradeRequest.getCardNo(), repayTradeRequest.getBankName());

            //更新银行卡信息
            TradeBank tradeBank = tradeBaseDomainFactory.composeTradeBank(repayTradeRequest, tradeBase.getTradeBank());
            tradeBase.setTradeBank(tradeBank);

            tradeBase.transferStatus(TradeActionEnum.LOAN_RETRY.getCode(),
                    TradeStatusEnum.MANUAL_CLOSED.getStatus(), "system", new Date(), new Date(), "update bank success");
            tradeBaseRepository.restore(tradeBase);
            LOGGER.info("updateBankInfoAndLoanMarket,重新绑卡处理成功,request:{}", JSON.toJSONString(repayTradeRequest));
            CreateTradeRequest request = new CreateTradeRequest();
            TTradeExtraEntity tTradeExtraEntity = tTradeExtraDao.selectByTradeNo(tradeNo);
            if (tTradeExtraEntity != null) {
                request.setAppCode(tTradeExtraEntity.getAppCode());
                TradeExtraData tradeExtraData = new TradeExtraData();
                BeanUtils.copyProperties(tTradeExtraEntity, tradeExtraData);
                request.setTradeExtraData(tradeExtraData);
            }
            request.setUsageOfLoan(tradeBase.getUsageOfLoan());
            request.setTradeType(tradeBase.getTradeOrderType());
            request.setClientType(tradeBase.getClientType());
            request.setDiscountList(null);
            request.setProductCode(tradeBase.getProductCode());
            request.setUserCode(tradeBase.getUserCode());
            request.setChannelCode(tradeBase.getChannelCode());
            request.setProductCategory(tradeBase.getProductCategory());
            request.setMerchantCode(tradeBase.getMerchantCode());
            this.createTrade(request);
            return Response.ok().putData(null);
        } catch (TradeException e) {
            LOGGER.error("重新绑卡失败,request:{}", JSON.toJSONString(repayTradeRequest));
            return Response.error("Bind card error");
        } catch (Exception e) {
            LOGGER.error("重新绑卡异常,request:{}", JSON.toJSONString(repayTradeRequest));
            return Response.error("Bind card error");
        }
    }

    /**
     * 构建成功的交易结果
     *
     * @param tradeBase
     */
    public void handlerSuccessCreateTradeResult(TradeBase tradeBase) {
        //推信审 全部走异步处理
        LOGGER.info("异步推信审,tradeNo:{}", tradeBase.getTradeNo());
        TradeTaskCenter tradeTaskCenter = new TradeTaskCenter()
                .setTaskRetryTimes(0)
                .setTaskStatus(TaskStatusEnum.INIT)
                .setTaskType(TaskTypeEnum.AUDIT)
                .setTradeNo(tradeBase.getTradeNo());
        tradeTaskCenterRepository.store(tradeTaskCenter);
    }

    /**
     * 签名回执
     *
     * @param signCallbackRequest
     * @return
     */
    @Override
    @ParamsValidate
    public Response signCallback(SignCallbackRequest signCallbackRequest) {
        String tradeNo = signCallbackRequest.getTradeNo();
        if (null == signCallbackRequest.getCapitalCode()) {
            LOGGER.info("== 签名资金方不能为空 ==,signCallbackRequest:{}", JSON.toJSONString(signCallbackRequest));
            return Response.error(TradeErrorCodeEnum.default_error, "sign error");
        }
        LOGGER.info("== 签名回执 ==,tradeNo:{} ", tradeNo);
        try {
            TradeBase tradeBase = tradeBaseRepository.load(signCallbackRequest.getTradeNo());
            if (tradeBase == null) {
                return Response.error(TradeErrorCodeEnum.trade_not_exist);
            }
            //签名成功
            if (signCallbackRequest.isSignSuccess()) {
                //交易状态迁转
                tradeBaseService.signSuccess(tradeBase);
                loanPublic(tradeBase, signCallbackRequest);
            } else {
                //交易状态迁转
                tradeBaseService.signFailed(tradeBase);
                tradeUniqueService.releaseUniqueLock(tradeBase);
                tradeBaseRepository.restore(tradeBase);
            }
            LOGGER.info("== 签名回执 成功==,tradeNo:{} ", signCallbackRequest.getTradeNo());
            return Response.ok().putData(null);
        } catch (TradeException e) {
            LOGGER.error("== 签名回执处理失败 ==,tradeNo:{},e ", tradeNo, e);
            return Response.error(TradeErrorCodeEnum.trade_not_exist);
        }
    }

    /**
     * 更新合同存储信息
     *
     * @param updateContractRequest
     * @return
     */
    @Override
    @ParamsValidate
    public Response updateContract(UpdateContractRequest updateContractRequest) {
        try {
            TTradeContractEntity tTradeContractEntity = new TTradeContractEntity();
            tTradeContractEntity.setTradeNo(updateContractRequest.getTradeNo());
            tTradeContractEntity.setContractUrl(updateContractRequest.getContractUrl());
            tTradeContractEntity.setSignDate(updateContractRequest.getSignDate());
            tTradeContractEntity.setVid(updateContractRequest.getVid());
            tTradeContractEntity.setDocumentId(updateContractRequest.getDocumentId());
            tTradeContractDao.updateByTradeNo(tTradeContractEntity);
            return Response.ok();
        } catch (Exception e) {
            return Response.error(TradeErrorCodeEnum.default_error);
        }
    }

    @Override
    public Response closeTradeAfterCheckSignName(String tradeNo) {
        if (true) {
            return Response.error();//接口废弃
        }

        try {
            TradeBase tradeBase = tradeBaseRepository.load(tradeNo);
            if (tradeBase == null) {
                return Response.error(TradeErrorCodeEnum.trade_not_exist);
            }

            tradeBase.setTradeOrderStatus(TradeStatusEnum.MANUAL_CLOSED);
            tradeBase.setTradeSignStatus(TradeSignStatusEnum.SIGN_NAME_NOT_MATCH);
            //tradeBase.setTradeAuditStatus(TradeAuditStatusEnum.AUDIT_FAILED);
            tradeBaseRepository.restore(tradeBase);
            tradeUniqueService.releaseUniqueLock(tradeBase);
            LOGGER.info("====== closeTradeAfterCheckSignName success, tradeNo:{} ======", tradeNo);
        } catch (Exception e) {
            LOGGER.error("====== closeTradeAfterCheckSignName exception, tradeNo:{} ======", tradeNo, e);
            return Response.error(TradeErrorCodeEnum.close_trade_failed);
        }
        return Response.ok();
    }

    @Override
    public Response completeHighMark(String tradeNo) {
        return Response.error("error!");
    }

    /**
     * 完成highmark
     *
     * @param tradeNo
     * @return
     */
    @Override
    public Response completeHighMarkV2(String tradeNo) {
        //通知信审系统 highmark完成
        LOGGER.info("completeHighMarkV2,tradeNo:{}", tradeNo);
        String value = redisClient.get(HIGH_MARK_TRADE_NO, tradeNo);
        if (StringUtils.isNotEmpty(value)) {
            return Response.error("Please try again");
        }
        redisClient.set(HIGH_MARK_TRADE_NO, tradeNo, 5, tradeNo);
        try {
            TradeBase tradeBase = tradeBaseRepository.load(tradeNo);
            if (tradeBase == null) {
                return Response.error("order not exist");
            }
            //回调幂等处理
            if (TradeStatusEnum.LOAN_WAITTING.equals(tradeBase.getTradeOrderStatus())
                    || TradeStatusEnum.REPAYMENT_WATTING.equals(tradeBase.getTradeOrderStatus())
                    || TradeStatusEnum.OVERDUE.equals(tradeBase.getTradeOrderStatus())
            ) {
                LOGGER.info("completeHighMarkV2,交易状态已不处于highmark,作通过处理,tradeNo:{}", tradeBase.getTradeNo());
                return Response.ok().putData(null);
            }
            if (tradeBase.getTradeOrderStatus() != TradeStatusEnum.AUDIT_WATTING
                    || !Objects.equals(tradeBase.getTradeAuditSubStatus(), TradeAuditSubStatusEnum.WAITING_HIGHMARK)) {
                LOGGER.info("completeHighMarkV2,交易状态不匹配,tradeNo:{}", tradeBase.getTradeNo());
                return Response.error("Order status error");
            }

            Response<UserHighmarkVo> userHighmarkByUserCode = userHighmarkService.getUserHighmarkByUserCode(tradeBase.getUserCode());
            if (userHighmarkByUserCode == null || userHighmarkByUserCode.getData() == null) {
                return Response.error("high mark report not exist");
            }

            tradeBase.setTradeAuditSubStatus(TradeAuditSubStatusEnum.INIT);
            tradeBaseRepository.restore(tradeBase);

            //这里必须先修改本地状态 再通知信审 不然会有数据操作并发问题
            boolean result = auditIntegrationService.pushHighmarkToAudit(tradeBase.getTradeNo());
            if (!result) {
                LOGGER.info("highmark通知信审失败,tradeNo:{}", tradeBase.getTradeNo());
                TradeTaskCenter tradeTaskCenter = new TradeTaskCenter()
                        .setTaskRetryTimes(0)
                        .setTaskStatus(TaskStatusEnum.INIT)
                        .setTaskType(TaskTypeEnum.HIGHMARK_TO_AUDIT)
                        .setTradeNo(tradeBase.getTradeNo());
                tradeTaskCenterRepository.store(tradeTaskCenter);
            }

            return Response.ok();
        } catch (Exception e) {
            LOGGER.error("completeHighMarkV2异常,tradeNo:{}", tradeNo, e);
            return Response.error("error!");
        }

    }

    /**
     * 提现确认
     *
     * @param withdrawCallbackRequest
     * @return
     */
    @Override
    public Response withdrawCallback(WithdrawCallbackRequest withdrawCallbackRequest) {
        String tradeNo = withdrawCallbackRequest.getTradeNo();

        LOGGER.info("withdrawCallback,tradeNo:{}", tradeNo);
        Object o = redisClient.get(RedisKeyConstant.WITHDRAW_CONFIRM_KEY, tradeNo);
        if (o != null) {
            return Response.error("Please try again");
        }
        redisClient.set(RedisKeyConstant.WITHDRAW_CONFIRM_KEY, tradeNo, 5, tradeNo);
        try {
            TradeBase tradeBase = tradeBaseRepository.load(tradeNo);
            if (tradeBase == null) {
                return Response.error("order not exist");
            }
            tradeBaseService.withdrawalConfirm(tradeBase);
            tradeBaseRepository.restore(tradeBase);

            //用户提现插入打款任务
            TradeTaskCenter tradeTaskCenter = new TradeTaskCenter()
                    .setTaskRetryTimes(0)
                    .setTaskStatus(TaskStatusEnum.INIT)
                    .setTaskType(TaskTypeEnum.PAY)
                    .setTradeNo(tradeBase.getTradeNo())
                    .setBizNo(tradeBase.getTradeNo());
            tradeTaskCenterRepository.store(tradeTaskCenter);

            return Response.ok();
        } catch (Exception e) {
            LOGGER.error("withdrawCallback异常,tradeNo:{}", tradeNo, e);
            return Response.error("error!");
        }
    }

    /**
     * 电子签+推单到pay
     *
     * @param tradeBase
     * @param signCallbackRequest
     */
    public void loanPublic(TradeBase tradeBase, SignCallbackRequest signCallbackRequest) {

        // 创建推单定任务
        if (StringUtils.isEmpty(tradeBase.getContractUrl())) {
            tradeBase.setContractUrl(signCallbackRequest.getContractUrl());
        }
        if (signCallbackRequest.getCapitalCode() != null) {
            tradeBase.setCapitalCode(signCallbackRequest.getCapitalCode());
        }
        tradeBase.setSignDate(signCallbackRequest.getSignDate());
        tradeBaseService.createPayTask(tradeBase, false);
        tradeBaseRepository.restore(tradeBase);
        //若合同不存在 则重新生成
        if (StringUtils.isEmpty(signCallbackRequest.getContractUrl()) && StringUtils.isEmpty(tradeBase.getContractUrl())) {
            String contractUrl = contractService.createContract(signCallbackRequest.getTradeNo());
            signCallbackRequest.setContractUrl(contractUrl);
        }
        //保存签名合同
        TTradeContractEntity tTradeContractEntity = new TTradeContractEntity();
        tTradeContractEntity.setTradeNo(signCallbackRequest.getTradeNo());
        tTradeContractEntity.setContractUrl(signCallbackRequest.getContractUrl());
        tTradeContractEntity.setSignDate(signCallbackRequest.getSignDate());
        tTradeContractEntity.setVid(signCallbackRequest.getVid());
        tTradeContractEntity.setDocumentId(signCallbackRequest.getDocumentId());
        tTradeContractDao.updateByTradeNo(tTradeContractEntity);
    }

    /**
     * 提现
     *
     * @param tradeBase
     * @param user
     */
    private void withdraw(TradeBase tradeBase, User user) {
        tradeBaseService.auditPassToWithdraw(tradeBase);
        //发短信
        messageIntegrationService.sendMessageAfterNeedWithdraw(tradeBase.getTradeNo(), tradeBase.getUserCode(), user.getMobile(), user.getName(), tradeBase.getBorrowTotalCapital().toString());
    }

    @Override
    public Response<Boolean> updateTradeChannelCodeByTradeNo(String tradeNo, String channelCode) {
        if (StringUtils.isEmpty(tradeNo) || StringUtils.isEmpty(channelCode)) {
            return Response.error(BasicErrorCodeEnum.PARAM_VALID_ERROR, "param can not be empty");
        }
        tradeBaseRepository.updateTradeByTradeNo(tradeNo, channelCode);
        return Response.ok().putData(true);
    }

    @Override
    @ParamsValidate
    public Response<CreateServiceResponse> createServiceFeePayment(CreateServiceFeeRequest request) {
        TServiceTradeEntity entity = new TServiceTradeEntity();
        BeanUtils.copyProperties(request, entity);
        entity.setCreateDate(new Date());
        entity.setServiceStatus(ServiceStatusEnum.INIT.getCode());
        String serviceNo = IdUtils.genId() + "SN";
        entity.setServiceNo(serviceNo);
        tServiceTradeDao.insert(entity);
        return Response.ok().putData(new CreateServiceResponse(serviceNo));
    }

    @Override
    @ParamsValidate
    public Response<Boolean> serviceFeePaymentCallBack(ServiceFeePaymentCallBackRequest request) {
        TServiceTradeEntity entity = tServiceTradeDao.selectByServiceNo(request.getServiceNo());
        if (entity == null) {
            return Response.error(BasicErrorCodeEnum.INTERNAL_SERVER_ERROR, "order not exist");
        }
        if (entity.getServiceStatus() == ServiceStatusEnum.SUCCESS.getCode()) {
            return Response.ok().putData(true);
        }
        entity.setServiceStatus(ServiceStatusEnum.SUCCESS.getCode());
        entity.setPaidAmount(new BigDecimal(request.getPaidAmount()));
        entity.setTripleSuccessDate(request.getTripleSuccessDate());
        entity.setAcceptNo(request.getAcceptNo());
        tServiceTradeDao.updateByPrimaryKey(entity);
        return Response.ok().putData(true);
    }

    @Override
    public Response<Boolean> copyOldUnpaidOrders(String mobile, String userCode, String extraInfo) {

        try {
            LOGGER.info("== 复制老的未还订单 开始==");
            List<TTradeEntity> oldUnpaidTradeListByMobile = tTradeDao.getOldUnpaidTradeListByMobile(mobile);
            if (CollectionUtils.isEmpty(oldUnpaidTradeListByMobile)) {
                LOGGER.info("== 复制老的未还订单 开始,没有未还订单==");
                return Response.ok().putData(true);
            }

            LOGGER.info("== 复制老的未还订单 ==，size:{}", oldUnpaidTradeListByMobile.size());
            List<TBillEntity> oldUnpaidBillListByMobile = tBillDao.getOldUnpaidBillListByMobile(mobile);
            if (CollectionUtils.isEmpty(oldUnpaidBillListByMobile)) {
                LOGGER.info("== 复制老的未还订单 账单为空==");
                return Response.ok().putData(true);
            }

            LOGGER.info("== 复制老的未还订单 账单不为空==");
            Map<String, TBillEntity> tradeBillMap = new HashMap<>();
            oldUnpaidBillListByMobile.forEach(tBillEntity -> {
                tradeBillMap.put(tBillEntity.getTradeNo(), tBillEntity);
            });

            LOGGER.info("== 复制老的未还订单 开始插入到当前数据库==");

            oldUnpaidTradeListByMobile.forEach(entity -> {
                TTradeEntity tTradeEntity = tTradeDao.selectOneByTradeNo(entity.getTradeNo());
                LOGGER.info("== 复制老的未还订单 当前数据库不存在相同数据==");
                if (tTradeEntity == null) {
                    ProductCategory categoryByCode = productIntegrationService.getCategoryByCode(entity.getProductCategory());
                    if (categoryByCode == null) {
                        LOGGER.info("== 复制老的未还订单 不存在当前类目==，productCagetory:{}", entity.getProductCategory());
                        return;
                    }

                    entity.setUserCode(userCode)
                            .setDiscountTotalCapital(new BigDecimal(0))
                            .setPaidTotalCapital(new BigDecimal(0))
                            .setPaidPeriod(0)
                            .setUsageOfLoan(1)
                            .setMerchantCode(categoryByCode.getMerchantCode())
                            .setGmtCreate(entity.getGmtCreate());


                    tTradeDao.copyInsert(entity);
                    tBillDao.copyInsert(tradeBillMap.get(entity.getTradeNo()));
                }

            });
        } catch (Exception e) {
            LOGGER.error("== 复制老的未还订单 账单为空,异常==", e);
            return Response.error().putData(false);
        }


        return Response.ok().putData(true);
    }
}
